<template>
  <div class="page d-flex flex-column m-t20">
     <el-main
             v-loading="isLoading"
             element-loading-text="loading……"
     >
         <el-form
                 ref="formRef"
                 label-width="130"
                 :model="form"
                 :rules="status===2?'':rules"
                 class="d-flex"
         >
             <div class="left-wrap">
                 <div class="d-flex a-center" v-if="status!==2">
                     <el-form-item label-width="80px" label="投资方案" prop="files">
                         <file-uploads
                                 ref="fileUploadsRef"
                                 @onSuccess="onSuccess"
                                 @on-select-file="onSelectFile"
                                 :disabled="status===2"
                         />
                     </el-form-item>
                 </div>
                 <div :class="[status===2?'box m-t50':'box m-t20']">
                     <div class="d-flex flex-column">
                         <label>方案预览:</label>
                         <div v-if="files.length !== 0" class="m-t10 d-flex flex-wrap">
                             <span @click="selectFileName(index,item)" :style="{color:currentIndex===index?'#fc702b':''}" class="m-r10 file-name" v-for="(item,index) in files" :key="index">{{item.fileName}}</span>
                         </div>
                     </div>
                     <div ref="contractContentRef" class="contract-content m-t10" id="demoDocContainer"/>
                 </div>
             </div>
             <div class="line"></div>
             <div class="right-wrap">
                 <div style="opacity: 0">
                     <label style="color: #1A1A1A;"></label>
                     <el-button class="m-l10" style="border-color: #FC7018;background-color:#fff8f6;color: #FC7018;">
                     </el-button>
                 </div>
                 <div class="box m-t20">
                     <label>关键信息编制：</label>
                     <div class="form-content m-t30">

                         <el-form-item label="方案名称" prop="planName">
                             <el-input :disabled="status===2" v-model="form.planName" placeholder="请输入方案名称"></el-input>
                         </el-form-item>
                         <el-form-item label="注册资本" prop="registerCapital">
                             <el-input
                                 :disabled="status===2"
                                 v-model="form.registerCapital"
                                 placeholder="请输入注册资本"
                                 @input="form.registerCapital = limitInputNum(form.registerCapital,8,2,true)"
                             ></el-input>
                         </el-form-item>
                         <el-form-item label="投资比例" prop="investmentRatio">
                             <el-input
                                 :disabled="status===2"
                                 v-model="form.investmentRatio"
                                 placeholder="请输入投资比例"
                                 @input="form.investmentRatio = limitInputNum(form.investmentRatio,3,0,false)"
                             ></el-input>
                         </el-form-item>
                         <el-form-item label="投资规模" prop="investmentScale">
                             <el-input
                                 :disabled="status===2"
                                 v-model="form.investmentScale"
                                 placeholder="请输入投资规模"
                             ></el-input>
                         </el-form-item>
                         <el-form-item label="拟计划总投额" prop="planAmount">
                             <el-input
                                     :disabled="status===2"
                                     v-model="form.planAmount"
                                     placeholder="请输入拟计划总投额"
                                     @input="form.planAmount = limitInputNum(form.planAmount,8,2,true)"
                             ></el-input>
                         </el-form-item>
                         <el-form-item label="年度计划投资额" prop="yearPlanAmount">
                             <el-input
                                     :disabled="status===2"
                                     v-model="form.yearPlanAmount"
                                     placeholder="请输入年度计划投资额"
                                     @input="form.yearPlanAmount = limitInputNum(form.yearPlanAmount,8,2,true)"
                             ></el-input>
                         </el-form-item>
                         <el-form-item label="合作方" prop="partnerId">
                             <el-select :disabled="status===2" v-model="form.partnerId" class="input-width" clearable multiple collapse-tags>
                                 <el-option v-for="(item,index) in data.partnerList" :key="index" :label="item.partnerName" :value="item.partnerId"></el-option>
                             </el-select>
                         </el-form-item>
                         <el-form-item label="方案描述" prop="planSummary">
                             <el-input
                                 :disabled="status===2"
                                 v-model="form.planSummary"
                                 :rows="5"
                                 type="textarea"
                                 placeholder="请输入方案描述"/>
                         </el-form-item>
                         <el-form-item label="会议议题名称" prop="meetingTopics">
                             <el-input :disabled="status===2" v-model="form.meetingTopics" placeholder="请输入会议议题名称"></el-input>
                         </el-form-item>
                         <el-form-item label="会审部门" prop="joinDepartmentIds">
                             <el-select :disabled="status===2" v-model="form.joinDepartmentIds" filterable class="input-width" clearable multiple collapse-tags>
                                 <el-option v-for="(item,index) in allDepartmentList" :key="index" :label="item.departmentName" :value="item.departmentId"></el-option>
                             </el-select>
                         </el-form-item>
                     </div>
                 </div>
                 <div v-if="status===2">
                     <label>审批结果：</label>
                     <el-form-item label="审批结果">
                         <el-input disabled :placeholder="{'1':'审批中','2':'已通过','3':'已驳回'}[form.status] || '暂无'"></el-input>
                     </el-form-item>
                     <el-form-item label="查看审批流程">
                          <el-button size="small" @click="toOA(form.oaUrl)" class="button_funtion2">查看审批流程</el-button>
                     </el-form-item>
                     <el-form-item label="创建时间">
                         <el-input disabled :placeholder="form.createTime || '暂无'"></el-input>
                     </el-form-item>
                     <el-form-item label="方案创建人">
                         <el-input disabled :placeholder="form.creator || '暂无'"></el-input>
                     </el-form-item>
                 </div>
             </div>
         </el-form>
         <div class="buttons-wrap d-flex j-center m-t30">
             <el-button
                     v-if="status === 1"
                     color="#FC7018"
                     style="color: #FFFFFF"
                     @click="nextStep"
             >提交审批</el-button>
             <el-button
                     v-if="status === 3"
                     color="#FC7018"
                     style="color: #FFFFFF"
                     @click="onSubmit"
             >重新提交</el-button>
         </div>
     </el-main>
  </div>
</template>

<script setup>
import {ElForm, ElFormItem, ElLoading, ElMessage, ElOption, ElSelect,ElMain} from "element-plus";
import {inject, nextTick, onMounted, reactive, ref, watch} from "vue";
import { renderAsync } from "docx-preview";
import {department, programmeManagementApi, reserveInvestmentProjectLibraryApi} from "@/api/investment";
import {blobToFile, limitInputNum, resetForm} from "@/common/utils/GlobalUtils";
import FileUploads from "../components/FileUploads.vue";

//导入PDFObject
import PDFObject from 'pdfobject'

const status = ref(0);

const allDepartmentList = ref([]);

const data = inject('state');

const files = ref([]);

const isLoading = ref(false);

const props = defineProps({
    currentProp:{
        type:Object,
        default:{}
    }
});

const form = reactive({
    projectId:'',
    planId:'',
    planName:'',
    planSummary:'',
    planAmount:'',
    registerCapital:'',
    investmentRatio:'',
    partnerId:'',
    investmentScale:'',
    urlKey:'',
    status:1,
    userIds:[],
    participants:'',
    participantIds:'',
    meetingTopics:'',
    meetingMinutes:'',
    files:[],
    yearPlanAmount:'',
    joinDepartmentIds:''
});

const rules = reactive({
    joinDepartmentIds: [
        { required: true, message: '请选择会审部门!', trigger: 'change' },
    ],
    meetingTopics: [
        { required: true, message: '会议议题名称不能为空!', trigger: 'blur' },
    ],
    yearPlanAmount: [
        { required: true, message: '年度计划投资额不能为空!', trigger: 'blur' },
    ],
    meetingMinutes: [
        { required: true, message: '会议纪要不能为空!', trigger: 'blur' },
    ],
    userIds: [
        { required: true, message: '请选择参会人员!', trigger: 'change' },
    ],
    planName: [
        { required: true, message: '方案名称不能为空!', trigger: 'blur' },
    ],
    planSummary: [
        { required: true, message: '方案描述不能为空!', trigger: 'blur' },
    ],
    planAmount: [
        { required: true, message: '计划金额不能为空!', trigger: 'blur' },
    ],
    registerCapital: [
        { required: true, message: '注册资本不能为空!', trigger: 'blur' },
    ],
    investmentRatio: [
        { required: true, message: '投资比例不能为空!', trigger: 'blur' },
    ],
    partnerId: [
        { required: true, message: '合作方不能为空!', trigger: 'change' },
    ],
    investmentScale: [
        { required: true, message: '投资规模不能为空!', trigger: 'blur' },
    ],
    files: [
        { required: true, message: '请上传附件!', trigger: 'change' },
    ],
});

const docxOptions =  {
    className: "kaimo-docx-666", // string：默认和文档样式类的类名/前缀
    inWrapper:  true, // boolean：启用围绕文档内容的包装器渲染
    ignoreWidth: false, // boolean：禁用页面的渲染宽度
    ignoreHeight: false, // boolean：禁止渲染页面高度
    ignoreFonts: false, // boolean：禁用字体渲染
    breakPages: true, // boolean：在分页符上启用分页
    ignoreLastRenderedPageBreak: true, // boolean：在 lastRenderedPageBreak 元素上禁用分页
    experimental: false, // boolean：启用实验功能（制表符停止计算）
    trimXmlDeclaration: true,  // boolean：如果为true，解析前会从 xml 文档中移除 xml 声明
    useBase64URL: false, // boolean：如果为true，图片、字体等会转为base 64 URL，否则使用URL.createObjectURL
    useMathMLPolyfill: false, // boolean：包括用于 chrome、edge 等的 MathML polyfill。
    showChanges: false, // boolean：启用文档更改的实验性渲染（插入/删除）
    debug: false, // boolean：启用额外的日志记录
}

const docxRender = (buffer) => {
    let bodyContainer = document.getElementById("demoDocContainer");
    renderAsync(
        buffer, // Blob | ArrayBuffer | Uint8Array, 可以是 JSZip.loadAsync 支持的任何类型
        bodyContainer, // HTMLElement 渲染文档内容的元素,
        null, // HTMLElement, 用于呈现文档样式、数字、字体的元素。如果为 null，则将使用 bodyContainer。
        docxOptions // 配置
    ).then(res => {
        console.log("res---->", res)
    });
}

/**
 * 跳转OA
 * @param url
 */
const toOA = (url) => {
  window.open(url);
}

/**
 * el-upload 选择文件后的事件
 * @param file
 */
const formRef = ref(null);
const uploadFile = (file) => {
    form.currentFile = file.file;
    formRef.value.clearValidate('currentFile');
    const downUrl = URL.createObjectURL(file.file)
    const a = document.createElement('a');
    a.innerHTML = file.file.name;
    a.href = downUrl
    a.download = file.file.name;
    a.target = '_blank';
    const addTypeArray = file.file.name.split(".");
    const addType = addTypeArray[addTypeArray.length - 1]

    if(addType === "docx" || addType === "pdf"){


    }else{
        ElMessage.error('请上传正确格式的文档!');
    }
}

/**
 * 文件移除
 */
const onRemove = () => {
    form.currentFile = '';
    form.urlKey = '';
    formRef.value.validateField('currentFile');
}

/**
 * 提交审核
 */
const submitForm  = (callback) => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            let loading = null;
            try {
                loading = ElLoading.service({
                    lock: true,
                    text: '提交审核中...',
                    background: 'rgba(0, 0, 0, 0.7)',
                });
                let params = {
                    ...form
                }
                if(Array.isArray(form.partnerId)){
                    params.partnerId = params.partnerId.join(',');
                }
                if(Array.isArray(form.joinDepartmentIds)){
                    params.joinDepartmentIds = params.joinDepartmentIds.join(',');
                }
                params.files = [];
                for (let item of form.files){
                    params.files.push({...item.data});
                }
                if (Array.isArray(form.userIds) &&  form.userIds.length!==0){
                    let tempArr = [];
                    params.participantIds = form.userIds.join(',');
                    form.userIds.forEach(item=>{
                        userList.value.forEach(val=>{
                            if(val.userId === item){
                                tempArr.push(val.userName);
                            }
                        });
                    });
                    params.participants = tempArr.join(',');
                }
                reserveInvestmentProjectLibraryApi.submitForApproval2(params).then(res=>{
                    if(res.code === '200'){
                        loading.close();
                        if(callback)callback();
                    }else{
                        loading.close();
                        ElMessage.error('提交表单异常!');
                    }
                });
            }catch (e) {
                loading.close();
                ElMessage.error('提交表单异常!');
            }
        } else {
            console.log('error submit!', fields)
        }
    });
}

/**
 * 下一步
 */
const emits = defineEmits(['nextStep']);
const nextStep = () => {
    submitForm(()=>{
        ElMessage.success('提交成功!');
        emits('nextStep','goSuccessPage');
    });
};

/**
 * 重新提交
 */
const onSubmit = () => {
    formRef.value.validate(async (valid, fields) => {
        if (valid) {
            let loading = null;
            try {
                loading = ElLoading.service({
                    lock: true,
                    text: '提交审核中...',
                    background: 'rgba(0, 0, 0, 0.7)',
                });
                let uploadFile = new FormData();
                uploadFile.append("file",form.currentFile);
                const res = await reserveInvestmentProjectLibraryApi.upload(uploadFile);
                form.urlKey = res.data;
                let params = {
                    ...form
                }
                if(Array.isArray(form.partnerId)){
                    params.partnerId = params.partnerId.join(',');
                }
                if (Array.isArray(form.userIds) &&  form.userIds.length!==0){
                    let tempArr = [];
                    params.participantIds = form.userIds.join(',');
                    form.userIds.forEach(item=>{
                        userList.value.forEach(val=>{
                            if(val.userId === item){
                                tempArr.push(val.userName);
                            }
                        });
                    });
                    params.participants = tempArr.join(',');
                }
                const res2 = await programmeManagementApi.editForApproval(params);
                if(res2.code === '200'){
                    loading.close();
                    ElMessage.success('提交成功!');
                    emits('nextStep','goSuccessPage');
                }else{
                    loading.close();
                    ElMessage.error('提交表单异常!');
                }
            }catch (e) {
                loading.close();
                ElMessage.error('提交表单异常!');
            }
        } else {
            console.log('error submit!', fields)
        }
    });
}

/**
 * 预览文档
 * @param fileName
 * @param res
 *
 */
const previewDocuments = (fileName,res) => {
    const addTypeArray = fileName.split(".");
    const addType = addTypeArray[addTypeArray.length - 1]
    let params = {'docx':'docx','pdf':'pdf'};
    if(params[addType]){
        let blob = new Blob([res],{
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
        });
        // let blob = new Blob([res],{
        //     type: 'application/pdf;charset=UTF-8'
        // });

        if(params[addType]==='docx'){
            nextTick(()=>{
                renderAsync(blob, contractContentRef.value);
            });
        }
        if(params[addType]==='pdf'){
            // 将blob转换为file
            let file = blobToFile(blob,new Date().getTime(),'application/pdf');
            // 将file转换为dataUrl
            let dataUrl = URL.createObjectURL(file);
            PDFObject.embed(dataUrl, '#demoDocContainer', { width: '100%' });
            setTimeout(()=>{
                URL.revokeObjectURL(dataUrl);
            },1000);
        }

    }
}

/**
 * 根据项目名称获取渲染后的word
 * @param templateUrlKey
 */
const contractContentRef = ref(null);
const getPlanWord = (templateUrlKey,callback,err_callback) => {
    reserveInvestmentProjectLibraryApi.getPlanWord({templateUrlKey:templateUrlKey}).then(res=>{
       if(res){
           previewDocuments(templateUrlKey,res);
           if(callback)callback();
       }
       if(res.code!==undefined && res.code!=='200'){
          if(err_callback)err_callback();
       }
    });
}

/**
 * 查询方案数据
 * @param projectId
 */
const getInvestmentPlanVo = (projectId) => {
    reserveInvestmentProjectLibraryApi.getInvestmentPlanVo({projectId:projectId})
        .then(res=>{
            const {code,data} = res;
            if(code === '200'){
                if(data.urlKey!==''){
                    getPlanWord(data.urlKey);
                }
                for (let k1 in data){
                    for (let k2 in form){
                        if(k1==='partnerId'){
                           if(data[k1]!==''){
                               form[k1] = data[k1].split(',');
                           }
                        }else if(k1==='joinDepartmentIds'){
                            form[k1] = data[k1].split(',');
                        }else if(k1 === k2){
                            form[k2] = data[k1];
                        }
                    }
                }
            }
        })
};

/**
 * 查询用户列表
 */
const userList = ref([]);
const getUserList = () => {
    department.getUserList().then(res=>{
        if(res.code === '200'){
            userList.value = res.data;
        }
    });
}

const fileUploadsRef = ref(null);

/**
 * 获取合同状态
 */
const getStatus = (projectId) => {
    isLoading.value = true;

    resetForm(form);
    setTimeout(()=>{
        if(formRef.value){
            formRef.value.clearValidate();
        }
    },200);
    document.getElementById('demoDocContainer').innerHTML = '';
    files.value = [];
    if(fileUploadsRef.value){
        fileUploadsRef.value.clearFiles();
    }

    form.projectId = projectId;
    programmeManagementApi.getProgramme({projectId:projectId}).then(res=>{
        if(res.code !=='200'){
            isLoading.value = false;
        }
        if(res.code === '200' && !res.data){
            status.value = 1;
            isLoading.value = false;
        }
        if(res.code === '200' && res.data){
            if(res.data.status === 3){
                status.value = 3;
                isLoading.value = false;
            }else {
                status.value = 2;
                isLoading.value = false;
            }

            if(res.data.files && Array.isArray(res.data.files) && res.data.files.length){
                files.value = res.data.files;
                getPlanWord(res.data.files[0].fileUrlKey,_=>{
                    isLoading.value = false;
                },_=>{
                    isLoading.value = false;
                });
            }


            for (let k1 in form){
                for (let k2 in res.data){
                    if(k2 === 'participantIds' && res.data[k2]!==''){
                        form['userIds'] = res.data[k2].split(',');
                    } else{
                        form[k2] =res.data[k2];
                    }
                }
            }
        }
    });
}

/**
 * 预览文档
 * @param file
 */
const previewDocument= (file) => {
    const addTypeArray = file.name.split(".");
    const addType = addTypeArray[addTypeArray.length - 1]
    let params = {'docx':'docx','pdf':'pdf'};
    if(params[addType]){
        // 将file转为buffer
        let fr = new FileReader();
        if(params[addType]==='docx'){
            fr.readAsArrayBuffer(file);
            fr.addEventListener("loadend",(e) => {
                let buffer = e.target.result;
                docxRender(buffer);
            },false);
        }
        if(params[addType]==='pdf'){
            let dataUrl = URL.createObjectURL(file);
            PDFObject.embed(dataUrl, '#demoDocContainer', { width: '100%' });
            setTimeout(()=>{
                URL.revokeObjectURL(dataUrl);
            },1000);

           /* fr.readAsDataURL(file) // 这里只需要将文件传进去就可以了
            fr.addEventListener("loadend",(e) => {
                let buffer = e.target.result;
                // 1.文件名 2.要将pdf渲染到的指定位置（dom元素） 3.指定在embed标签中的显示的宽度
                PDFObject.embed(buffer, '#demoDocContainer', { width: '100%' });
            },false);*/
        }

    }
}

/**
 * 移除文档
 */
const removeDocument = () => {
    const parentEl = document.querySelector("#demoDocContainer");
    const childEls = parentEl.querySelectorAll("*");
    for (let item of childEls){
        item.style.display = 'none';
    }
}


/**
 * 上传文件后成功时的回调
 * @param files
 */
const onSuccess = (files) => {
  form.files = files;
  if(form.files.length!==0){
      previewDocument(form.files[0].file);
  }
  if(form.files.length===0){
      removeDocument();
  }
}

/**
 * 选择文件的事件
 * @param file
 */
const onSelectFile = (file) => {
    previewDocument(file);
}

defineExpose({
    getStatus
});

watch(()=> [data.title,data.row],(value)=>{
    if(value[0]==='编辑' && value[1]!==null){
        getInvestmentPlanVo(value[1].projectId);
    }
},{deep: true,immediate:true});

watch(()=>[data.row,props.currentProp],(value)=>{
    if(value[0]!==null && props.currentProp.projectId!==undefined){
      form.projectId = value[1].projectId;
    } if(value[0]===null && props.currentProp.projectId!==undefined){
      form.projectId = value[1].projectId;
    }
    if(value[0]!==null && props.currentProp.projectId===undefined){
        form.projectId = value[0].projectId;
    }
},{deep:true,immediate:true});

const currentIndex = ref(0);
/**
 * 选择文件
 * @param index
 * @param item
 */
const selectFileName = (index,item) => {
    isLoading.value = true;
    getPlanWord(item.fileUrlKey,_=>{
        isLoading.value = false;
    },_=>{
        isLoading.value = false;
    });
    currentIndex.value = index;
}

// 获取所有部门
const getAllDepartments = () => {
    department.getAllDepartments().then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
            allDepartmentList.value = data;
        }
    });
};

onMounted(()=>{
    getUserList();
    getAllDepartments();
});
</script>

<style>
.contract-content .kaimo-docx-666-wrapper{
   background: none;
}
</style>

<style lang="scss" scoped>
.form-item-content{
    all: unset;
}

.input-width{
    width: 100% !important;
}

.file-name{
  cursor: pointer;
}

.upload-icon{
  width: 18px;
  height: 18px;
}
.page{
  position: relative;
  .left-wrap{
    flex: 1;
    .box{
      width: 100%;
      height: 100%;
      .contract-content{
        width: 500px;
        height: 600px;
        background-color: #d8d8d8;
        border: 1px solid #979797;
        border-radius: 5px;
        overflow: auto;
      }
    }
  }
  .line{
    width: 1px;
    height: 70vh;
    background-color: #E3E7F1;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(- 50%,- 50%) scaleX(.5);
  }
  .right-wrap{
    flex: 1;
    margin-left: 100px;
    margin-top: 18px;
  }
}
</style>
